
import unittest
import diabind
import testdata
import os

class LineNumberTest( unittest.TestCase ):

    def __get_func(self):
        if not hasattr(self, "__func"):
            glob = testdata.loaded_session.get_globalScope()
            enum = glob.findChildren( diabind.SymTagFunction,
                                      "DllMain",
                                      diabind.nsfUndecoratedName )
            self.assertEqual(len(enum), 1)
            self.__func = enum[0]
        return self.__func

    def __get_lines(self, length):
        rva = self.__get_func().get_relativeVirtualAddress()
        return testdata.loaded_session.findLinesByRVA(rva, length)

    def test_compiland(self):
        enum_lines = self.__get_lines(1)
        self.assertEqual(len(enum_lines), 1)

        lib_name = enum_lines[0].get_compiland().get_libraryName()
        self.assertEqual(lib_name[lib_name.rfind("\\"):].lower(), "\\dllmain.obj")

        name = enum_lines[0].get_compiland().get_name()
        self.assertEqual(name[name.rfind("\\"):].lower(), "\\dllmain.obj")

        self.assertEqual(enum_lines[0].get_compiland().get_symTag(), diabind.SymTagCompiland)

    def test_sourceFile(self):
        enum_lines = self.__get_lines(1)
        self.assertEqual(len(enum_lines), 1)

        self.assertTrue(len(enum_lines[0].get_sourceFile().get_fileName()) > 0)

    def test_lineNumber(self):
        enum_lines = self.__get_lines(0x100)
        self.assertTrue(len(enum_lines) > 1)

        self.assertTrue(enum_lines[0].get_lineNumber() <= enum_lines[0].get_lineNumberEnd())
        self.assertTrue(enum_lines[0].get_lineNumberEnd() < enum_lines[1].get_lineNumber())
        self.assertTrue(enum_lines[1].get_lineNumber() <= enum_lines[1].get_lineNumberEnd())

    def test_address(self):
        enum_lines = self.__get_lines(1)
        self.assertEqual(len(enum_lines), 1)

        func = self.__get_func()

        self.assertEqual(enum_lines[0].get_addressSection(), func.get_addressSection())
        self.assertEqual(enum_lines[0].get_addressOffset(), func.get_addressOffset())
        self.assertEqual(enum_lines[0].get_relativeVirtualAddress(), func.get_relativeVirtualAddress())
        self.assertEqual(enum_lines[0].get_virtualAddress(), func.get_virtualAddress())

    def test_length(self):
        enum_lines = self.__get_lines(0x100)
        self.assertTrue(len(enum_lines) > 1)

        self.assertTrue(enum_lines[0].get_length() >= 1)
        self.assertTrue(enum_lines[1].get_length() >= 1)
